package org.example.tx.acl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class AclService {

    private static final BeanPropertyRowMapper<AccessControlEntry> ACE_ROW_MAPPER = new BeanPropertyRowMapper<>(AccessControlEntry.class);
    private static final BeanPropertyRowMapper<AccessControlList> ACL_ROW_MAPPER = new BeanPropertyRowMapper<>(AccessControlList.class);
    private static final SingleColumnRowMapper<Integer> INT_ROW_MAPPER = new SingleColumnRowMapper<>(Integer.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public AccessControlList read(int id) {
        var acl = jdbcTemplate.queryForObject(
                "select * from acl where id = ?",
                ACL_ROW_MAPPER,
                new Object[]{id});

        var aces = jdbcTemplate.query(
                "select * from ace where aclId = ? order by seq",
                ACE_ROW_MAPPER,
                new Object[]{id});

        for (AccessControlEntry ace : aces) {
            acl.add(ace);
        }

        return acl;
    }

    @Transactional
    public void update(int id) {
        int version = lock(id);
        log.info("locked {},{}", id, version);
        updateVersion(id, version);
        var read = read(id);
        log.info("updated {}", read);
    }


    private Integer lock(int id) {
        return jdbcTemplate.queryForObject(
                "select version from acl where id = ? for update",
                INT_ROW_MAPPER,
                new Object[]{id});
    }

    private void updateVersion(int id, int version) {

        version += 1;

        //log.info("update acl#{} version to {}", id, version);
        jdbcTemplate.update(
                "update acl set version = ? where id = ?",
                new Object[]{version, id});

        //log.info("update acl#{}.aces version to {}", id, version);
        jdbcTemplate.update(
                "update ace set version = ? where aclId = ?",
                new Object[]{version, id});
    }
}
